<?php

namespace App\Services;

use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use AntChain\SECURITYTECH\Client as AntChainSECURITYTECHClient;

use AntChain\SECURITYTECH\Models\Config;
use AntChain\SECURITYTECH\Models\BizParam;
use AntChain\SECURITYTECH\Models\BizQueryParam;
use AntChain\SECURITYTECH\Models\QueryRiskGeneralRequest;
use App\Exceptions\BaseException;
use App\Models\MemberOther;
use App\Models\OrderRiskAlipay;
use App\Models\OtherOrderAllocate;
use function alipay\aop\addPKCS7Padding;


/**
 * 支付宝履约等级
 */
class AlipayRiskService {

    /**
     * 使用AK&SK初始化账号Client
     * @param string $accessKeyId
     * @param string $accessKeySecret
     * @return AntChainSECURITYTECHClient Client
     */
    public static function createClient($accessKeyId, $accessKeySecret){
        $config = new Config([]);
        // 您的AccessKey ID
        $config->accessKeyId = $accessKeyId;
        // 您的AccessKey Secret
        $config->accessKeySecret = $accessKeySecret;
        $config->endpoint="openapi.antchain.antgroup.com";
        $config->protocol="https";
        return new AntChainSECURITYTECHClient($config);
    }

    /**
     * 开发环境三要素密钥
     */
    private static  $DEV_PUK = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA5czwxivEfJOfIp+vFB8NZee16ORu+cni2mLkAfqcDCGFPARkX9bejm8vJ3fnEww7Rr0PvY5DiWhtdfpUz+Wjvb6u2a9N23ltw84h6eMQ2lGjPSWoiqd4mKqsaY2FGzqp0Q9vrZgzU2qcioNGJMA1BG+s6xXK+xX/3vY+Dma4EXmB5bupdi/5fNNewl2OKyN6pKbDfir8VkPRgByUxcM05a+38x0+eiaqSFEsG4SXAePbwOACmIWuddenTJTgNZvBSBiFImDLDhOa49t2hYeXA4u+Gu4vRFKa4TkVA/rLW0Fe9NSOwX4Ehr01T93wssunMYcF3QWhcx4s1KvDc6HUEwIDAQAB";
    /**
     * 生产环境三要素密钥
     */
    private static  $PROD_PUK = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAr2fEaFGdjzP13Pc+p0mizNlJKXs242WGoUxtEuCqBmtT3H1/WKj3tcR5I3Ex+JfNSQ+C5Id+7upO6EvgeXtDpeZA08ljtGRB8BwyBaUM0sPslw40IQ8Deyd2VXcZNtTouYyC7xBSfMM4ZKrCvG/NMT051brS9bAvJ9kbM/buIHivg5nndf+UECu5Dllvz8QT5oVE6pZOvURrenFHiWY2yLXmopW9n/hsJHEB6L+5U6YQt/lbgOUA3JnntJykTKYACZ6ONWMJS6UT/TMH5x45yqihVfkboGl7ubQkmYGY+aKRlTQzDmt2DXJqHv2/Fa//Cqu95tqIIhW1peNqSEm54wIDAQAB";

    /**
     * 使用RSA进行加密
     *
     * @param content
     * @return
     * @
     */
    private static function encryptInDev($content)
    {
        $public_key = "-----BEGIN PUBLIC KEY-----\n" . self::$PROD_PUK . "\n-----END PUBLIC KEY-----";
        return self::encryptByPublicKey($content, openssl_pkey_get_public($public_key));
    }

    /**
     * 使用公钥进行RSA非对称加密
     *
     * @param data
     * @param key
     * @return
     * @
     */
    public static function encryptByPublicKey($data, $key)
    {
        if (!is_string($data)) {
            return null;
        }
        $r = openssl_public_encrypt($data, $encrypted,  $key,OPENSSL_PKCS1_PADDING);
        return base64_encode($encrypted);
    }




    /**
     * 履约风险识别
     * @param string[] $args
     * @return void
     */
    public static function levelPerformance($cert_no,$userId,$member_id){
        $client = self::createClient(config('antchain.accessKeyId'), config('antchain.accessKeySecret'));
        $aesKey='4f66405c4fc6405c';
        $hashCertNo=self::AesEncrypt(hash("sha256",$cert_no),$aesKey);
        $bizQueryParam0BizParam0 = new BizParam([
            "paramValue" =>$hashCertNo,
            "paramKey" => "CERT_NO"
        ]);
        $bizQueryParam0 = new BizQueryParam([
            "bizParams" => [
                $bizQueryParam0BizParam0
            ]
        ]);

        $queryRiskGeneralRequest = new QueryRiskGeneralRequest([
            "encryptedNonce" => self::encryptInDev(base64_encode($aesKey)),
            "userAuthorization" => "1",
            "bizQueryParams" => [
                $bizQueryParam0
            ],
            "dataCode" => "nsf_general_rental_v1_3_hundred_cert"
        ]);
        $RAAS_PRODUCTS='nsf_general_found';
        $headers = array("X-AntCloud-Gw-Ext-Flag" => "{\"raas_products\":\"" . $RAAS_PRODUCTS . "\"}");
        $result=obToArray($client->queryRiskGeneralEx($queryRiskGeneralRequest,$headers,new RuntimeOptions()));
        $data='';
        if (isset($result['resultCode']) && $result['resultCode'] == 'OK') {
            $flag =  true;
            $data=$result['resultList'][0]['riskResults'][0]['riskData'][0]['resultValue'];

//            0-1 A1
//2-3 A2
//4-6 B1
//7-9 B2
//10-17 C1
//18-25 C2
//26-62 D1
//63-99 D2
            if($data==1){
                $data=$data.'(A1)';
            }
            if($data==2||$data==3){
                $data=$data.'(A2)';
            }
            if($data>=4&&$data<=6){
                $data=$data.'(B1)';
            }
            if($data>=7&&$data<=9){
                $data=$data.'(B2)';
            }
            if($data>=10&&$data<=17){
                $data=$data.'(C1)';
            }
            if($data>=18&&$data<=25){
                $data=$data.'(C2)';
            }
            if($data>=26&&$data<=62){
                $data=$data.'(D1)';
            }
            if($data>=63){
                $data=$data.'(D2)';
            }

            OtherOrderAllocate::where('member_id',$member_id)->increment('alipayRiskCount');
            $member=MemberOther::where('id',$userId)->first();
            OrderRiskAlipay::setRiskData($member['cert_name'],$member['cert_no'],$member['mobile'],$data,1,$result,$userId,$member_id,$hashCertNo);
        }else{
            $data='未知';
            $flag =  false;
            $member=MemberOther::where('id',$userId)->first();
            OrderRiskAlipay::setRiskData($member['cert_name'],$member['cert_no'],$member['mobile'],$data,2,$result,$userId,$member_id,$hashCertNo);
        }
        MemberOther::where('id',$userId)->update(['level_performance'=>$data]);
        return $data;

    }


    /**
     * 获取证书长度
     * @param type $Key_String
     * @param type $Key_Type
     * @return int
     * @throws BaseException
     */
    private static function get_Key_Size($Key_String,$Key_Type=true){
        $Key_Temp=array();
        try{
            if($Key_Type){//私钥
                $Key_Temp = openssl_pkey_get_details(openssl_pkey_get_private($Key_String));
            }else if(openssl_pkey_get_public($Key_String)){//公钥
                $Key_Temp = openssl_pkey_get_details(openssl_pkey_get_public($Key_String));
            }else{
                throw new BaseException("Is not a key");
            }
            IF(array_key_exists("bits",$Key_Temp)){
                return $Key_Temp["bits"];
            }else{
                return 0;
            }
        } catch (BaseException $ex){
            $ex->getTrace();
            return 0;
        }
    }


    public static function AesEncrypt($str,$screct_key){
        $cipherText = openssl_encrypt($str, 'AES-128-ECB', $screct_key, OPENSSL_RAW_DATA);
        return base64_encode($cipherText);
    }

    /**
     * 填充算法
     * @param string $source
     * @return string
     */
  public static function addPKCS7Padding($source)
    {
        $source = trim($source);
        $block = 16;

        $pad = $block - (strlen($source) % $block);
        if ($pad <= $block) {
            $char = chr($pad);
            $source .= str_repeat($char, $pad);
        }
        return $source;
    }

}
